//
//  ViewController.m
//  自作画板
//
//  Created by Jorn.Wu on 15/6/29.
//  Copyright (c) 2015年 Jorn.Wu. All rights reserved.
//

#import "ViewController.h"
#import "JWPaintView.h"
#import "MBProgressHUD+MJ.h"

@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet JWPaintView *paintView;
@property (weak, nonatomic) IBOutlet UISlider *slide;
- (IBAction)btnOnclick:(UIButton *)sender;
- (IBAction)clearOnclick:(id)sender;
- (IBAction)undoOnclick:(id)sender;
- (IBAction)eraserOnclick:(id)sender;
- (IBAction)selectedPicture:(id)sender;
- (IBAction)saveOnclick:(id)sender;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.slide addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
}
- (void)valueChange:(UISlider *)slider{
    _paintView.lineWidth = slider.value;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)btnOnclick:(UIButton *)sender {
    _paintView.color = sender.backgroundColor;
}

- (IBAction)clearOnclick:(id)sender {
    [_paintView clearScreen];
}

- (IBAction)undoOnclick:(id)sender {
    [_paintView undo];
}

- (IBAction)eraserOnclick:(id)sender {
    [_paintView eraser];;
}

- (IBAction)selectedPicture:(id)sender {
    //图片选择器
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    //数据源
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//枚举类型
    
    picker.delegate = self;//通过代理来实现（必须实现代理方法或代理的数据源方法）
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *img = info[UIImagePickerControllerOriginalImage];//图片
    _paintView.img = img;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)saveOnclick:(id)sender {
    //一般保存到用户相册里
    //原来是把画板截屏
    
    //开启图形上下文
    UIGraphicsBeginImageContextWithOptions(_paintView.bounds.size, NO, 0.0);
    //获取当前上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //把画板上的内容渲染到图形上下文
    [_paintView.layer renderInContext:context];
    
    //获取图片
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    //关闭图上下文
    UIGraphicsEndImageContext();
    //保存到用户的相册里
    UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
    
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {//保存失败
        [MBProgressHUD showError:@"保存失败！"];
    }else {//成功
        [MBProgressHUD showSuccess:@"保存成功！"];
    }
}
@end












